package com.hycloud.cloudstack.common;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class CsSignature {
	//private String apikey = "V0REe8c9cy8MBFZYfrqCFzihd56eDRntlY5OtRhOJapZIwkG6NM8qrvC6qC3qyfjSHWKvFm-r8ijLWlF-TV4Vw";
	//private String seckey = "R6fGwetBVc6_-CErGFVYIzyMSfC18O3YgpR6jYHijyEDg1MxFREr14S4C3LxsGyGkEwHep5nUuD1Slr6tMDTRw";
//	private String apikey = "plgWJfZK4gyS3mOMTVmjUVg-X-jlWlnfaUJ9GAbBbf9EdM-kAYMmAiLqzzq1ElZLYq_u38zCm0bewzGUdP66mg";
//	private String seckey = "VDaACYb0LV9eNjTetIOElcVQkvJck_J_QljX_FcHRj87ZKiy0z0ty0ZsYBkoXkY9b7eq1EhwJaw7FF3akA3KBQ";
	private static boolean json = true;
	
	
	public static String url(String url,String apikey,String seckey,Map<String,String> maps) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException{
		String surl = url;
		surl+=("&apikey="+apikey);
		if(maps!=null){
			maps.remove("command");
			for(Map.Entry<String, String> entry:maps.entrySet()){
				surl+="&"+entry.getKey()+"="+URLEncoder.encode(entry.getValue(), "UTF-8");
			}
		}
		if(json){
			surl+="&response=json";
		}
		String[] urls = surl.split("\\?"); 
		String cdnUrl = urls[1]; 
		cdnUrl = sort(cdnUrl);
		String turl = urls[0]+"?"+cdnUrl+"&signature="+signature(cdnUrl.toLowerCase(),seckey);
		
		return turl;
	}
	
	private static String signature(String cdnUrl,String seckey ) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec keySpec = new SecretKeySpec(seckey.getBytes(),
                "HmacSHA1");
        mac.init(keySpec);
        mac.update(cdnUrl.getBytes());
        byte[] encryptedBytes = mac.doFinal();
        return URLEncoder.encode(new String(Base64.encodeBase64(encryptedBytes)),"UTF-8");
    }
	
	
	private static String sort(String url){
		TreeMap<String, String> map = new TreeMap<String,String>(new Comparator<Object>() {
            public int compare(Object s1, Object s2) {
               return ((String)s1).compareTo((String)s2);
		         }
		});
		String[] kvStrings = url.split("&");
		for(String kvString:kvStrings){
			String[] kvArray = kvString.split("=");
			map.put(kvArray[0], kvArray[1]);
		}
		StringBuffer sb = new StringBuffer();
		for(String key:map.keySet()){
			sb.append("&"+key+"="+map.get(key));
		}
		return sb.substring(1);
	}
	
	
	
}
